package com.cjk.console.tunnel;

import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cjk.foundation.util.PropertyUtil;
import com.cjk.foundation.util.ShellUnit;

public class TunnelInit {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(TunnelInit.class);

	public TunnelInit() {
		init();
	}

	private void init() {
		ResourceBundle bundle = ResourceBundle.getBundle("config/tunnel");
		
		final String localhost = PropertyUtil.parseStringProperty(bundle, "tunnel.local.host");
		TunnelConfig.setSshdHost(localhost);
		
		final Integer localPort = PropertyUtil.parseIntProperty(bundle, "tunnel.local.port");
		TunnelConfig.setSshdPort(localPort);
		
		final String tunnelUser = PropertyUtil.parseStringProperty(bundle, "tunnel.creat.user");
		TunnelConfig.setSshUser(tunnelUser);
		
		final Integer localStartPort = PropertyUtil.parseIntProperty(bundle, "tunnel.local.start.port");
		TunnelConfig.setLocalStartPort(localStartPort);
		
		final Integer localEndPort = PropertyUtil.parseIntProperty(bundle, "tunnel.local.end.port");
		TunnelConfig.setLocalEndPort(localEndPort);
		
		String command = PropertyUtil.parseStringProperty(bundle, "tunnel.creat.command");
		command = command.replace("[--[sshdHost]--]", localhost);
		command = command.replace("[--[sshdPort]--]", String.valueOf(localPort));
		command = command.replace("[--[username]--]", tunnelUser);
		
		TunnelConfig.setCommand(command);
		
		
		
		String TOMACT_SERVER_PATH = this.getClass().getClassLoader().getResource("/").getPath();
		
		if (TOMACT_SERVER_PATH == null || TOMACT_SERVER_PATH.isEmpty()) {
			TOMACT_SERVER_PATH = "/install/tomcat/webapps/service/WEB-INF/classes/";
		}

		TunnelSystemShell.setTunnelShellPath(TOMACT_SERVER_PATH + "/script/");
		String tunnelShellPath = TunnelSystemShell.getTunnelShellPath();
		
		String destoryTunnelShell = PropertyUtil.parseStringProperty(bundle, "tunnel.shell.destroy.tunnel");
		if (destoryTunnelShell != null) {
			TunnelSystemShell.setDestoryTunnel(tunnelShellPath + destoryTunnelShell);
		} else {
			LOGGER.error("Failed to init Tunnel's property !!!   {}, is empty", "cloud.tunnel.shell.destroy.tunnel");
			return;
		}
		
		initShell();
	}
	
	/**
	 * shell脚本赋权限
	 */
	private void initShell() {
		String cmd = "chmod +x " + TunnelSystemShell.getTunnelShellPath() + "/*";
		ShellUnit.runShellCmd(cmd);
	}
}
